package com.inspur.cloud.controller;

import com.inspur.cloud.entity.dataspace.UserThreadLocal;
import com.inspur.cloud.entity.dataspace.common.OpResult;
import com.inspur.cloud.exception.ApiException;
import com.inspur.cloud.exception.BusinessException;
import com.inspur.cloud.util.ExceptionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.AccessDeniedException;

@RestControllerAdvice
public class RestControllerHandler {

    private static final Logger log = LoggerFactory.getLogger(RestControllerHandler.class);

    @ExceptionHandler(value = ApiException.class)
    public OpResult apiExceptionHandler(HttpServletRequest request, ApiException e) {
        recordLog(request, e);
        OpResult result = new OpResult();
        result.setMsg("系统异常" + (e.getMessage() == null ? "" : ":" + e.getMessage()));
        result.setCode(-1);
        return result;
    }

    @ExceptionHandler(value = BusinessException.class)
    public OpResult businessExceptionHandler(HttpServletRequest request, BusinessException e) {
        recordLog(request, e);
        OpResult result = new OpResult();
        result.setMsg(e.getMessage() == null ? "" : ":" + e.getMessage());
        result.setCode(-1);
        return result;
    }

    @ExceptionHandler(value = AccessDeniedException.class)
    public OpResult accessDeniedExceptionHandler(HttpServletRequest request, AccessDeniedException e) {
        recordLog(request, e);
        OpResult result = new OpResult();
        result.setMsg(e.getMessage());
        result.setCode(-1);
        return result;
    }

    @ExceptionHandler(value = Exception.class)
    public OpResult exceptionHandler(HttpServletRequest request, Exception e) {
        recordLog(request, e);
        OpResult result = new OpResult();
        result.setMsg("系统异常" + (e.getMessage() == null ? "" : ":" + e.getMessage()));
        result.setCode(-1);
        return result;
    }

    private void recordLog(HttpServletRequest request, Exception e) {
        try {
            StringBuffer sb = new StringBuffer();
            sb.append("Url: ").append(request.getRequestURI()).append("\r\n");
            sb.append("Body: ").append(request.getQueryString()).append("\r\n").append(UserThreadLocal.getValue("requestBody")).append("\r\n");
            sb.append("Error: ").append(ExceptionHelper.getExceptionDetail(e)).append("\r\n");
            log.error(sb.toString());
        } catch (Exception ex) {

        }
    }
}
